<template>
  <view class="w100 pb-20">
    <uni-card padding="0">
      <view class="inforClass pt-20">实践任务填报</view>
      <view class="w100 rowsb rowsm h-100">
        <view class="w100 rowsb rowsm h100 border-botm">
          <view class="fs-28 col333 fw-b">实践任务名称：{{ taskName }}</view>
        </view>
      </view>
      <view class="w100 rowsb rowsm h-100">
        <view class="w100 rowsb rowsm h100 border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践报告名称：</view>
          <input type="text" placeholder="请输入实践报告名称" :style="{ 'color': projectName !== null ? '#000' : '#a9a9a9' }"
            v-model="projectName">
        </view>
      </view>
      <view class="w100 rowsb rowsm h-100">
        <view class="w100 rowsb rowsm h100 pr-20 border-botm" @tap="show = true">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践开始时间：</view>
          <view v-if="startTime" style="color: #000">{{ startTime.slice(0, 16) }}</view>
          <view v-else class="fs-28 col888">请选择实践开始时间</view>
        </view>
      </view>
      <u-datetime-picker :show="show" mode="datetime" v-model="value1" @confirm="confirmStartTime"
        @cancel="show = false"></u-datetime-picker>
      <view class="w100 rowsb rowsm h-100">
        <view class="w100 rowsb rowsm h100 pr-20 border-botm" @tap="endTimeShow = true">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践结束时间：</view>
          <view v-if="endTime" style="color: #000">{{ endTime.slice(0, 16) }}</view>
          <view v-else class="fs-28 col888">请选择实践结束时间</view>
        </view>
      </view>
      <u-datetime-picker :show="endTimeShow" mode="datetime" v-model="value1" @confirm="confirmEndTime"
        @cancel="endTimeShow = false"></u-datetime-picker>
      <view class="w100 rowsb rowsm h-100">
        <view class="w100 rowsb rowsm h100 border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践地点：</view>
          <input type="text" placeholder="请输入实践地点" :style="{ 'color': practicePlace !== null ? '#000' : '#a9a9a9' }"
            v-model="practicePlace">
        </view>
      </view>
    </uni-card>

    <uni-card padding="0">
      <view class="inforClass pt-20">实践详细说明</view>
      <textarea style="width: 100%" placeholder="请输入您的实践说明(必填)" :style="{ 'color': detail !== null ? '#000' : '#a9a9a9' }"
        v-model="detail" />
    </uni-card>
    <uni-card padding="0">
      <view class="inforClass pt-20">填报附件</view>
      <view class="w100 pl-12 pr-12 mb-20">
        <view class="w100 h-140 br-10 rows rowsm pl-40 mb-10" style="background-color: #F7F6FA;" @click="choseFile">
          <image src="/static/icon_cs.png" class="w-50 h-60 mr-20" mode=""></image>
          <view class="fs-26 col888">
            <view class="fs-24">须知: 图片最多6张、文件最多1个最大10M、视频最多1个最大100M,且附件为必填项</view>
            <view>（可上传word、pdf、图片、视频）</view>
          </view>
        </view>

        <view>
          <view class="w100 h-140 br-10 rowsb rowsm pl-40" style="background-color: #F7F6FA;"
            v-for="(item, index) in fileList" :key="index">
            <view class="rows rowsm w-420">
              <image src="/static/file.png" class="w-60 h-60 mr-20" mode=""></image>
              <view class="fs-28 col888 w100 one_overflow">{{ item.fileName }}</view>
            </view>
            <view class="w-120 h-60 br-30 rowsc rowsm colfff fs-24"
              style="background: linear-gradient(to bottom,#4897FF,#4878FF);" @click="handelDelete(item)">删除</view>
          </view>
        </view>
      </view>
    </uni-card>
    <view class="w100 rowsa rowsm mt-20 mb-20">
      <view class="w-300 h-84 br-42 rowsc rowsm colfff" style="background: linear-gradient(to bottom,#4897FF,#4878FF);"
        @click="submit()">提交</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      value1: Number(new Date()),
      workStartFlag: '',
      workEndFlag: '',
      show: false,
      endTimeShow: false,
      projectName: '',
      practicePlace: '',
      detail: '',
      type: '1',
      file: '',
      fileType: '',
      fileName: '',
      id: '',
      fileList: [],
      startTimePoke: '',
      endTimePoke: '',
      startTime: '',
      endTime: '',
      taskName: '',
      taskType: ''
    };
  },
  onLoad(e) {
    this.taskName = e.taskName;
    this.id = e.id;
    this.taskType = e.title;
    uni.setNavigationBarTitle({
      title: e.title + '填报'
    })
  },
  methods: {
    hideKeyboard() {
      uni.hideKeyboard();
    },

    choseFile() {
      // if (this.fileList.length === 5) return this.$tools.showtt('最多上传5个文件');
      let currentTotalSize = this.fileList.reduce((acc, item) => {
        return acc + item.size;
      }, 0);
      // const type = this.taskType == '劳动教育' ? 'ldjy' : this.taskType == '职业素养' ? 'zysj' : this.taskType == '应急安全' ? 'yjaqjy' : this.taskType == '思想实践教育' ? 'sxsjjy' : 'cxcyjy'
      uni.showActionSheet({
        itemList: ['图片', '文件', '视频'],
        success: (index, e) => {
          if (index.tapIndex === 0) {
            let imgNum = 0;
            this.fileList.forEach((itemImg) => {
              if (itemImg.fileType === '图片') {
                imgNum++;
              }
            });
            if (imgNum === 6) {
              this.$tools.showtt('最多可以只能上传6张图片');
              return
            }
            uni.chooseImage({
              count: 6 - this.fileList.length,
              sizeType: ['compressed'], // 选择压缩后的图片
              success: (res) => {
                res.tempFilePaths.forEach(item => {
                  // 检查单个文件大小，6MB = 6 * 1024 * 1024
                  // if (res.tempFiles[0].size > 10 * 1024 * 1024) {
                  //   this.$tools.showtt('图片大小不能超过6MB');
                  //   return;
                  // }
                  // 检查总文件大小
                  // currentTotalSize += res.tempFiles[0].size;
                  // if (currentTotalSize > 6 * 1024 * 1024) {
                  //   this.$tools.showtt('附件总大小不能超过6MB');
                  //   currentTotalSize -= res.tempFiles[0].size; // 回退当前大小
                  //   return;
                  // }

                  // this.compressImage(item).then((compressedFilePath) => {
                    uni.uploadFile({
                      url: this.$tools.httpOne + 'utils/ossUpload',
                      filePath: item,
                      name: 'file',
                      header: {
                        'Authorization': "Bearer " + sessionStorage.getItem('token')
                        // 'token': sessionStorage.getItem('token')
                      },
                      success: (res1) => {
                        if (JSON.parse(res1.data).code === 200) {
                          this.fileList.push({
                            fileName: JSON.parse(res1.data).originalFilename,
                            // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                            fileType: '图片',
                            file: JSON.parse(res1.data).url,
                            // type: type,
                          });
                        } else {
                          this.$tools.showtt(JSON.parse(res1.data).msg);
                        }
                      }
                    });
                  })
                // });
              }
            });
          }
          if (index.tapIndex === 1) {
            if (this.fileList.find(v => v.fileType == '文件')) {
              this.$tools.showtt('最多只能上传一个文件');
              return
            }
            uni.chooseFile({
              count: 1,
              type: 'file',
              maxFileSize: 10 * 1024 * 1024, // 最大文件大小，单位为字节，这里是10MB
              success: (res) => {
                uni.uploadFile({
                  url: this.$tools.httpOne + 'utils/ossUpload',
                  filePath: res.tempFilePaths[0],
                  header: {
                    'Authorization': "Bearer " + sessionStorage.getItem('token')
                    // 'token': sessionStorage.getItem('token')
                  },
                  name: 'file',
                  success: (res1) => {
                    const data = JSON.parse(res1.data);
                    if (data.code === 200) {
                      const fileExtension = data.originalFilename.split('.').pop().toLowerCase();
                      const allowedExtensions = ['txt', 'pdf', 'doc', 'docx', 'ppt', 'xlsx', 'xls']; // 允许的文件扩展名列表
                      if (allowedExtensions.includes(fileExtension)) {
                        this.fileList.push({
                          fileName: data.originalFilename,
                          // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                          fileType: '文件',
                          file: data.url,
                          // type: type
                        });
                      } else {
                        this.$tools.showtt('上传文件仅支持txt、pdf、word、excel、ppt');
                      }
                    } else {
                      this.$tools.showtt('上传失败');
                    }
                  }
                });
              }
            });
          }
          function checkFileSize(fileSize, maxSize) {
            if (fileSize > maxSize) {
              uni.showToast({
                title: `文件大小不能超过 ${maxSize / 1024 / 1024}MB`,
                icon: 'none'
              });
              return false;
            }
            return true;
          }
          if (index.tapIndex === 2) {
            if (this.fileList.find(v => v.fileType == '视频')) {
              this.$tools.showtt('最多只能上传一个视频');
              return
            }
            uni.chooseVideo({
              sourceType: ['album', 'camera'],
              compressed: true, // 启用自动压缩
              maxFileSize: 60 * 1024 * 1024, // 最大文件大小，单位为字节，这里是10MB
              success: (res) => {
                // 检查文件大小是否超过50MB
                if (!checkFileSize(res.size, 60 * 1024 * 1024)) {
                  return;
                }
                uni.uploadFile({
                  url: this.$tools.httpOne + 'utils/ossUpload',
                  filePath: res.tempFilePath,
                  name: 'file',
                  header: {
                    'Authorization': "Bearer " + sessionStorage.getItem('token')
                    // 'token': sessionStorage.getItem('token')
                  },
                  success: (res1) => {
                    if (JSON.parse(res1.data).code === 200) {
                      this.fileList.push({
                        fileName: JSON.parse(res1.data).originalFilename,
                        // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                        fileType: '视频',
                        file: JSON.parse(res1.data).url,
                        // type: type
                      });
                    } else {
                      this.$tools.showtt('上传失败');
                    }
                  }
                });
              }
            });
          }
        }
      });

    },
    // 图片压缩函数
    compressImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: filePath,
          success: (imageInfo) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();

            img.onload = () => {
              const MAX_WIDTH = 800; // 最大宽度
              const MAX_HEIGHT = 800; // 最大高度
              let width = img.width;
              let height = img.height;

              if (width > height && width > MAX_WIDTH) {
                height = (height / width) * MAX_WIDTH;
                width = MAX_WIDTH;
              } else if (height > width && height > MAX_HEIGHT) {
                width = (width / height) * MAX_HEIGHT;
                height = MAX_HEIGHT;
              }

              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, 0, 0, width, height);

              canvas.toBlob((blob) => {
                const newFilePath = URL.createObjectURL(blob);
                resolve(newFilePath);
              }, 'image/jpeg', 0.8); // 压缩质量
            };
            console.log(imageInfo.path);
            img.src = imageInfo.path;
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    // 劳动开始时间
    confirmStartTime(e) {
      if (this.endTimePoke && this.endTimePoke < e.value) {
        this.$tools.showtt('开始时间大于结束时间,请重新选择')
        return
      }
      this.startTimePoke = e.value;
      const date = new Date(e.value);
      // 获取年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
      const day = String(date.getDate()).padStart(2, '0');

      // 获取小时和分钟
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      // 组合成完整的日期时间字符串
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;

      this.startTime = formattedDate;
      // const formattedDate = new Date(e.value).toLocaleString(); // 转为本地时间字符串
      // this.startTime = formattedDate.split('/').join("-");
      this.show = false;

    },
    //  劳动结束时间
    confirmEndTime(e) {
      if (this.startTimePoke && this.startTimePoke > e.value) {
        this.$tools.showtt('结束时间小于开始时间,请重新选择')
        return
      }
      this.endTimePoke = e.value;
      const date = new Date(e.value);
      // 获取年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
      const day = String(date.getDate()).padStart(2, '0');

      // 获取小时和分钟
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      // 组合成完整的日期时间字符串
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
      this.endTime = formattedDate;
      // const formattedDate = new Date(e.value).toLocaleString(); // 转为本地时间字符串
      // this.endTime = formattedDate.split('/').join("-");
      this.endTimeShow = false;
    },

    handelDelete(item) {
      this.fileList.splice(this.fileList.findIndex(v => v.fileName === item.fileName), 1)
    },

    submit() {
      if (this.fileList.length == 0) return this.$tools.showtt('附件不得为空!')
      if (!this.projectName) return this.$tools.showtt('请输入项目')
      if (!this.startTime) return this.$tools.showtt('请选择时间')
      if (!this.endTime) return this.$tools.showtt('请选择时间')
      if (!this.practicePlace) return this.$tools.showtt('请输入地点')
      if (!this.detail) return this.$tools.showtt('请输入详情说明')
      let data = {
        projectName: this.projectName,
        practiceStartTime: this.startTime + ':00',
        practiceEndTime: this.endTime + ':59',
        practicePlace: this.practicePlace,
        detail: this.detail,
        studentFileList: this.fileList,
        practiceTaskId: this.id
      }
      // if(!this.id){
      this.$tools.axiosFromToken('POST', 'practice/user/add', { ...data }, '加载中').then(res => {
        this.$tools.showtt(res.msg)
        if (res.code != 200) return
        setTimeout(() => {
          this.$tools.goBack(2)
        }, 1000)
      })
      // }else {
      //   this.$tools.axiosFromToken('POST','prold/update',{...data},'加载中').then(res => {
      //     this.$tools.showtt(res.msg)
      //     if(res.code != 200) return
      //     setTimeout(() => {
      //       this.$tools.goBack(2)
      //     },1000)
      //   })
      // }
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #fff;
}

.inforClass {
  font-size: 16px;
  font-weight: 700;
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.inforClass::before {
  content: '';
  width: 5px;
  height: 20px;
  background-color: #007AFF;
  margin-right: 5px;
  display: inline-block;
}

.mark {
  text-align: right;
  color: #f92929;
}

.border-botm {
  border-bottom: 1px #f1f1f1 solid;
}
</style>
